package com.heatingcharge.service.sys.impl;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.heatingcharge.common.util.LevelUtil;
import com.heatingcharge.dto.MenuLevelDTO;
import com.heatingcharge.entity.sys.SysMenu;
import com.heatingcharge.entity.sys.SysRole;
import com.heatingcharge.entity.sys.SysRoleMenu;
import com.heatingcharge.mapper.sys.SysMenuMapper;
import com.heatingcharge.service.sys.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heatingcharge.service.sys.ISysRoleMenuService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 菜单权限表 服务实现类
 * </p>
 *
 * @author devin.jiang
 * @since 2019-06-27
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    ISysRoleMenuService sysRoleMenuService;
    @Override
    public List<String> findPermsByUserId(Integer userId) {
        return baseMapper.findPermsByUserId(userId);
    }

    @Override
    public List<MenuLevelDTO> getMenus() {
        List<SysMenu> menuList=baseMapper.selectList(null);
        List<MenuLevelDTO> dtoList= Lists.newArrayList();
        for (SysMenu menu:menuList){
            MenuLevelDTO dto= MenuLevelDTO.adapt(menu);
            dtoList.add(dto);
        }
        return menuDtoListToTree(dtoList);
    }

    @Override
    public List<Integer> getMenuIdsByRoleId(Integer roleId) {
        return baseMapper.findMenuIdsByRoleId(roleId);
    }

    /**
     * 保存指定角色的菜单 ID
     * @param roleId
     * @param menuIds
     * @return
     */
    @Override
    public Integer saveRoleMenus(Integer roleId, List<Integer> menuIds) {
        //1 删除当前角色的所有menuID
        sysRoleMenuService.deleteByRoleId(roleId);

        if (menuIds.size()>0){
            SysRoleMenu sysRoleMenu;
            List<SysRoleMenu> sysRoleMenus=Lists.newArrayList();
            for (int i=0;i<menuIds.size();i++){
                sysRoleMenu=SysRoleMenu.builder()
                        .roleId(roleId)
                        .menuId(menuIds.get(i))
                        .build();
                sysRoleMenus.add(sysRoleMenu);
            }
           return sysRoleMenuService.saveBatch(sysRoleMenus) ?1:0;
        }
        return null;
    }

    private List<MenuLevelDTO> menuDtoListToTree(List<MenuLevelDTO> dtoList) {
        if (CollectionUtils.isEmpty(dtoList)){
            return Lists.newArrayList();
        }
        Multimap<String,MenuLevelDTO> levelMenuMap= ArrayListMultimap.create();
        List<MenuLevelDTO> rootList=Lists.newArrayList();
        for (MenuLevelDTO dto:dtoList){
            levelMenuMap.put(dto.getLevel(),dto);
            if (LevelUtil.ROOT.equals(dto.getLevel())){
                rootList.add(dto);
            }
        }
        // 按照seq从小到大排序
//        Collections.sort(rootList, new Comparator<MenuLevelDTO>() {
//            public int compare(MenuLevelDTO o1, MenuLevelDTO o2) {
//                return o1.getSeq() - o2.getSeq();
//            }
//        });
        // 递归生成树
        transformMenuTree(rootList, LevelUtil.ROOT, levelMenuMap);
        return rootList;
    }

    /**
     * 递归部门树
     * @param menuLevelList
     * @param level
     * @param levelMenuMap
     */
    private void transformMenuTree(List<MenuLevelDTO> menuLevelList, String level, Multimap<String, MenuLevelDTO> levelMenuMap) {
        for (int i = 0; i < menuLevelList.size(); i++) {
            // 遍历该层的每个元素
            MenuLevelDTO menuLevelDto = menuLevelList.get(i);
            // 处理当前层级的数据
            String nextLevel = LevelUtil.calculateLevel(level, menuLevelDto.getId());
            // 处理下一层
            List<MenuLevelDTO> tempMenuList = (List<MenuLevelDTO>) levelMenuMap.get(nextLevel);
            if (CollectionUtils.isNotEmpty(tempMenuList)) {
                // 排序
                //Collections.sort(tempMenuList, menuSeqComparator);
                // 设置下一层部门
                menuLevelDto.setChildren(tempMenuList);
                // 进入到下一层处理
                transformMenuTree(tempMenuList, nextLevel, levelMenuMap);
            }
        }
    }

//    public Comparator<MenuLevelDTO> menuSeqComparator = new Comparator<MenuLevelDTO>() {
//        public int compare(MenuLevelDTO o1, MenuLevelDTO o2) {
//            return o1.getSeq() - o2.getSeq();
//        }
//    };
}
